package cn.yunyichina.provider.register.service.impl;

import cn.yunyichina.provider.framework.dubbo.service.*;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.hisiface.register.CancelRegisterVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.RefundRegisterVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.StopRegisterVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.StopRegisterVoResponse;
import cn.yunyichina.provider.iface.entity.message.AppMessageVo;
import cn.yunyichina.provider.iface.entity.message.TemplateCode;
import cn.yunyichina.provider.iface.entity.order.OrderRegSchedulerVo;
import cn.yunyichina.provider.register.utils.RegUtil;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;


/**
 * 停诊服务
 * Created by Administrator on 2017/5/15.
 */
@Service
public class StopRegServiceImpl {

    private Logger logger = LoggerFactory.getLogger(StopRegServiceImpl.class);

    @Resource
    private Properties yaml;

    /**
     * 停诊对外接口
     * yyt.register.stop.reg.out
     *
     * @param data
     * @param sessionId
     * @return
     * @throws Exception
     */
    public Response outStopReg(String data, String sessionId) throws Exception {
//        logger.info("停诊对外接口,yyt.register.stop.reg.out,data= " + data);
        Log.i(LogScene.REGISTER_STOP, "yyt.register.stop.reg.out", LogParamType.REQUEST, "",
                "停诊对外接口 request=" + data);
        Response response = new Response();
        Map<String, String> map = JsonUtils.parseObject(data, Map.class);
        String orderList = map.get("order_list");
        if (StringUtils.isBlank(orderList)) {
            response.setResultCodeAndMessage("63001", "orderlist cannot be null");
            return response;
        }

        Response ordResponse = BaseService.callHumpFromInternal("yyt.base.order.by.order.nos.list", data);
        if (!"0".equals(ordResponse.getResultCode())) {
            response.setResultCodeAndMessage(ordResponse.getResultCode(), ordResponse.getResultMessage());
            return response;
        }

        List<OrderExtVo> list = JsonUtils.parseArray(ordResponse.getResult(), OrderExtVo.class);
        try {
            dealStop(list);//停诊逻辑处理
            response.setResultCodeAndMessage("0", "成功");
        } catch (Exception e) {
            e.printStackTrace();
            response.setResultCodeAndMessage("63000", "停诊出错！！");
        }
        return response;
    }

    /**
     * 停诊轮询
     * yyt.register.stop.reg.loop
     *
     * @param data
     * @param sessionId
     * @return
     * @throws Exception
     */
    public Response loopStopReg(String data, String sessionId) throws Exception {
        Response response = new Response();
        Map<String, String> map = JsonUtils.parseObject(data, Map.class);
        String hospitalCode = map.get("hospital_code");

        StopRegisterVo stopRegRequest = new StopRegisterVo();
        stopRegRequest.setHospitalCode(hospitalCode);
        stopRegRequest.setBranchCode(map.get("branch_code"));

        Calendar calendar = Calendar.getInstance();
        Date startTime = calendar.getTime();
        String endDate;
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour == 22) {
            endDate = DateUtils.dateToString(DateUtils.getDateEnd(DateUtils.getNextMonth(new Date(), 1)));
        } else {
            endDate = DateUtils.dateToString(DateUtils.getDateEnd(startTime));
        }
        stopRegRequest.setBeginTime(DateUtils.dateToString(startTime));
        stopRegRequest.setEndTime(endDate);
        ResCommon resCommon = HisifaceService.getHisifaceClient().stopRegister(stopRegRequest);
        Log.i(LogScene.REGISTER_STOP, "yyt.register.stop.reg.loop", LogParamType.REQUEST, stopRegRequest.getHospitalCode(),
                "call his stopRegister request=" + JsonUtils.toJsonString(stopRegRequest));
        Log.i(LogScene.REGISTER_STOP, "yyt.register.stop.reg.loop", LogParamType.RESPONSE, stopRegRequest.getHospitalCode(),
                "call his stopRegister response=" + JsonUtils.toJsonString(resCommon));

        if (!"0".equals(resCommon.getResultCode())) {
            //调用his查询停诊信息失败
            response.setResultCodeAndMessage(resCommon.getResultCode(), resCommon.getResultMessage());
            return response;
        }
        List<StopRegisterVoResponse> stopRegVoList = JsonUtils.parseArray(JsonUtils.toJsonString(resCommon.getResult()), StopRegisterVoResponse.class);

        String psOrdNums = "";
        String hisOrdNums = "";
        String doctors = "";
        String beginScheduleTime = "";//按医生代码查询订单的日期范围
        String endScheduleTime = "";
        String doctorCodes = "";
        for (StopRegisterVoResponse stopRegVo : stopRegVoList) {
            if (StringUtils.isNotBlank(stopRegVo.getYytOrdNum())) {
                psOrdNums += stopRegVo.getYytOrdNum() + ",";
            } else if (StringUtils.isNotBlank(stopRegVo.getHisOrdNum())) {
                hisOrdNums += stopRegVo.getHisOrdNum() + ",";
            } else {
                if (StringUtils.isBlank(beginScheduleTime) || beginScheduleTime.compareTo(stopRegVo.getRegisterDate()) > 0) {
                    beginScheduleTime = stopRegVo.getRegisterDate();
                }
                if (StringUtils.isBlank(endScheduleTime) || endScheduleTime.compareTo(stopRegVo.getRegisterDate()) < 0) {
                    endScheduleTime = stopRegVo.getRegisterDate();
                }
                doctorCodes += "'" + stopRegVo.getDoctorCode() + "',";
                doctors += "CONCAT(\"" + stopRegVo.getDoctorCode() + "\",\"" + stopRegVo.getRegisterDate() + "\"),";
            }
        }

        Response ordResponse = null;
        Map<String, String> query = new HashedMap();

        if (StringUtils.isNotBlank(psOrdNums)) {
            psOrdNums = psOrdNums.substring(0, psOrdNums.length() - 1);
            query.put("order_list", psOrdNums);
            ordResponse = BaseService.callHumpFromInternal("yyt.base.order.by.order.nos.list", JsonUtils.toJsonString(query));
        } else if (StringUtils.isNotBlank(hisOrdNums)) {
            hisOrdNums = hisOrdNums.substring(0, hisOrdNums.length() - 1);
            query.put("his_order_no_list", hisOrdNums);
            ordResponse = BaseService.callHumpFromInternal("yyt.base.order.by.his.order.nos.list", JsonUtils.toJsonString(query));
        } else if (StringUtils.isNotBlank(doctors)) {
            query.put("org_code", "'" + hospitalCode + "'");
            query.put("begin_schedule_time", "'" + beginScheduleTime + " 00:00:00" + "'");
            query.put("end_schedule_time", "'" + endScheduleTime + " 23:59:59" + "'");
            query.put("doctor_codes", doctorCodes.substring(0, doctorCodes.length() - 1));
            doctors = doctors.substring(0, doctors.length() - 1);
            query.put("doctor_condition", doctors);
            ordResponse = BaseService.callHumpFromInternal("yyt.base.order.by.doctors.list", JsonUtils.toJsonString(query));
        }

        logger.info("停诊业务处理,base返回" + JsonUtils.toJsonString(ordResponse));
        if (ordResponse != null && "0".equals(ordResponse.getResultCode())) {
            List<OrderExtVo> orderList = JsonUtils.parseArray(ordResponse.getResult(), OrderExtVo.class);
            logger.info("停诊业务处理 查询出的records : {}", JsonUtils.toJsonString(orderList));

            if (!CollectionUtils.isEmpty(orderList)) {
                List<OrderExtVo> stopOrderList = new ArrayList<>();//停诊订单列表

                //根据查订单的三种条件分别处理

                if (StringUtils.isNotBlank(doctors)) {
                    //按医生查询出来的记录，要比较就诊时间
                    for (Iterator<OrderExtVo> iter = orderList.iterator(); iter.hasNext(); ) {
                        OrderExtVo order = iter.next();
                        Map<String, String> extraParamsMap = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                        String beginTime = extraParamsMap.get("begin_time");
                        String endTime = extraParamsMap.get("end_time");

                        for (StopRegisterVoResponse vo : stopRegVoList) {
                            if (StringUtils.isNotBlank(vo.getWorkId())) {
                                //排班id不为空 按排班id比较
                                if(vo.getWorkId().equals(extraParamsMap.get("work_id"))){
                                    executeRealLogicalByFlag(stopOrderList, order, vo);
                                }
                            } else {
                                if (order.getDoctorCode().equals(vo.getDoctorCode()) &&
                                        order.getScheduleTime().substring(0, 10).equals(vo.getRegisterDate()) &&
                                        beginTime.compareTo(vo.getBeginTime()) >= 0 &&
                                        endTime.compareTo(vo.getEndTime()) <= 0) {
                                    executeRealLogicalByFlag(stopOrderList, order, vo);
                                }
                            }
                        }
                    }
                } else if (StringUtils.isNotBlank(psOrdNums)) {
                    for (Iterator<OrderExtVo> iter = orderList.iterator(); iter.hasNext(); ) {
                        OrderExtVo order = iter.next();
                        for (StopRegisterVoResponse vo : stopRegVoList) {
                            if (vo.getYytOrdNum().equals(order.getOrderNo())) {
                                executeRealLogicalByFlag(stopOrderList, order, vo);
                            }
                        }
                    }
                } else {
                    for (Iterator<OrderExtVo> iter = orderList.iterator(); iter.hasNext(); ) {
                        OrderExtVo order = iter.next();
                        for (StopRegisterVoResponse vo : stopRegVoList) {
                            if (vo.getHisOrdNum().equals(order.getHisOrderNo())) {
                                executeRealLogicalByFlag(stopOrderList, order, vo);
                            }
                        }
                    }
                }
                //停诊业务处理
                if (!CollectionUtils.isEmpty(stopOrderList)) {
                    dealStop(stopOrderList);
                }

            }
        }
        return ordResponse;
    }

    private void executeRealLogicalByFlag(List<OrderExtVo> stopOrderList, OrderExtVo order, StopRegisterVoResponse vo) {
        // flag 停诊：1（默认） 改诊：2  替诊：3
        if ("2".equals(vo.getFlag())) {
            dealChange(order, vo);
        } else if ("3".equals(vo.getFlag())) {
            dealReplace(order, vo.getReplaceDoctorName(), vo.getReplaceDoctorCode());
        } else {
            stopOrderList.add(order);
        }
    }

    /**
     * 改诊业务处理，查询，发短信，更改分时时间、状态
     *
     * @param stopRegVo
     */
    private void dealChange(OrderExtVo order, StopRegisterVoResponse stopRegVo) {

        String orgCode = order.getOrgCode();

        String stopRegMsgType = RegUtil.getRule(orgCode, RegUtil.STOP_REG_MSG_TYPE, "");//停诊消息推送方式

        /****发送消息*****/
        if (stopRegMsgType.indexOf("2") >= 0) {
            //发送服务窗消息
            sendChangeMessage(order, stopRegVo, "2");
        }
        //更新订单表
        order.setOrderStatusRevision();
        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        extraParams.put("revision_date",stopRegVo.getRevisionDate());
        extraParams.put("revision_begin_time", stopRegVo.getRevisionBeginTime());
        extraParams.put("revision_end_time", stopRegVo.getRevisionEndTime());
        order.setExtraParams(JsonUtils.toJsonString(extraParams));
        BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));

    }

    /**
     * 停改诊业务逻辑处理,一家医院的orderList
     *
     * @param orderList
     */
    private void dealStop(List<OrderExtVo> orderList) {

        if (CollectionUtils.isEmpty(orderList)) {
            logger.info("停诊业务处理 列表为空");
            return;
        }
//        logger.info("停诊业务处理 时间段符合的record : {}", JsonUtils.toJsonString(orderList));
        Log.i(LogScene.REGISTER_STOP, "yyt.register.stop.reg.loop", LogParamType.NORMAL, "",
                "停诊业务处理 时间段符合的record :" + JsonUtils.toJsonString(orderList));
        String orgCode = orderList.get(0).getOrgCode();

        String[] stopRegLimit = RegUtil.getRule(orgCode, RegUtil.STOP_REG_TIME_LIMIT, "1").split(",");//停诊退费时间限制
        int stopRegLimitValue = 1;//停诊退费时间限制
        int stopRegLimitType = Integer.parseInt(stopRegLimit[0]);
        if (stopRegLimit.length > 1) {
            stopRegLimitValue = Integer.parseInt(stopRegLimit[1]);
        }
        String isStopRegRefundHis = RegUtil.getRule(orgCode, RegUtil.IS_STOP_REG_REFUND_HIS, "1");//停诊是否执行退费
        String isStopRegUnlock = RegUtil.getRule(orgCode, RegUtil.IS_STOP_REG_UNLOCK, "1");//停诊是否执行号源释放
        String stopRegMsgType = RegUtil.getRule(orgCode, RegUtil.STOP_REG_MSG_TYPE, "");//停诊消息推送方式


        for (OrderExtVo order : orderList) {
            short stopStatus = 1;//停诊处理状态，初始为成功

            if (order.getOrderStatus() == OrderExtVo.ORDER_STATUS_CHANGE) {
                logger.info("该订单已经停诊处理过，不再重复处理" + order.getOrderNo());
                continue;
            }

            OrderRegSchedulerVo schedulerVo = OrderService.getOrderClient().selectOrderRegSchedulerById(order.getId());
            if (schedulerVo == null) {
                schedulerVo = parseOrder(order);
                OrderService.getOrderClient().addOrderRegScheduler(schedulerVo);//加到定时任务中间表
            }
            /****发送消息*****/
            logger.info("停诊业务处理,获取推送的方式为->" + JSON.toJSONString(stopRegMsgType));
            if (stopRegMsgType.indexOf("2") >= 0) {
                //发送服务窗消息
                sendAlipayMessage(schedulerVo);
            }

            if (stopRegMsgType.indexOf("3") >= 0) {
                //发送公众号消息
                sendWechatMessage(schedulerVo);
            }

            if (stopRegMsgType.indexOf("4") >= 0) {
                //停诊短信推送
                sendCodeAliDy(schedulerVo, 1);
            }

            String regType = RegUtil.getRegType(order.getScheduleTime().substring(0, 10));
            boolean isRefundHis;//是否his退费
            boolean isRefundPay;//是否第三方退费

            Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
            String beginTime = "00:00", endTime = "23:59";
            if (extraParams != null) {
                beginTime = (String) extraParams.get("begin_time");
                endTime = (String) extraParams.get("end_time");
            }

            Date scheduleDate = DateUtils.StringToDateYMD(order.getScheduleTime());//就诊日期
            //就诊开始时间
            Date scheduleStartTime = DateUtils.StringToDate(order.getScheduleTime().substring(0, 10) + " " + beginTime + ":00");
            Date scheduleEndTime = DateUtils.StringToDate(order.getScheduleTime().substring(0, 10) + " " + endTime + ":00");

            GregorianCalendar scheduleCalendar = new GregorianCalendar();
            Long nowTime = new Date().getTime();
            Long overTime = null;
            /**
             *  取消挂号截止时间点
             *  1、不限制 就诊当天几点
             *  2、就诊当天几点
             *  3、就诊时间段开始前多少分钟
             *  4、就诊时间段结束前多少分钟
             */
            switch (stopRegLimitType) {
                case 1:
                    //不限制情况  当前时间+1 始终使overTime > nowTime
                    overTime = nowTime + 1;
                    break;
                case 2:
                    //2、就诊当天几点
                    scheduleCalendar.setTime(scheduleDate);
                    scheduleCalendar.set(Calendar.HOUR_OF_DAY, stopRegLimitValue);
                    overTime = scheduleCalendar.getTimeInMillis();
                    break;
                case 3:
                    //3、就诊时间段开始前多少分钟
                    scheduleCalendar.setTime(scheduleStartTime);
                    overTime = scheduleCalendar.getTimeInMillis() - stopRegLimitValue * 60 * 1000;
                    break;
                case 4:
                    //就诊时间段结束前多少分钟
                    scheduleCalendar.setTime(scheduleEndTime);
                    overTime = scheduleCalendar.getTimeInMillis() - stopRegLimitValue * 60 * 1000;
                    break;
                case 5:
                    scheduleCalendar.setTime(scheduleDate);
                    scheduleCalendar.add(Calendar.DATE, -1);
                    scheduleCalendar.set(Calendar.HOUR_OF_DAY, stopRegLimitValue);
                    overTime = scheduleCalendar.getTimeInMillis();
                    break;
                case 6:
                    //不允许情况  当前时间11 始终使overTime < nowTime
                    overTime = nowTime - 1;
                    break;
            }

            if (nowTime >= overTime) {
                //超出时间限制或不允许退费
                isRefundHis = false;
                isRefundPay = false;
            } else {
                if ("1".equals(isStopRegRefundHis)) {//停诊是否执行退费通知
                    isRefundHis = true;
                } else {
                    isRefundHis = false;
                }
                isRefundPay = true;
            }

            if (order.getPayStatus() < 3) {
                //免支付预约单不退费
                isRefundHis = false;
                isRefundPay = false;
            }

            /****调用his退费开始*****/
            if (isRefundHis) {
                RefundRegisterVo refundRegisterVo = new RefundRegisterVo();
                if ("1".equals(order.getIsInsurance())) {
                    //医保退款
                    refundRegisterVo.setRefundAmount(String.valueOf(order.getTotalAmount()));
                    Map<String, String> ybMap = new HashedMap();
                    ybMap.put("cancel_serial_no", (String) extraParams.get("cancel_serial_no"));
                    ybMap.put("cancel_bill_no", (String) extraParams.get("cancel_bill_no"));
                    refundRegisterVo.setExtendParams(JSONObject.toJSONString(ybMap));
                } else {
                    //            refundRegisterVo.setRefundAmount(String.valueOf(order.getPayAmount()));
                    refundRegisterVo.setRefundAmount("2000");//test
                    refundRegisterVo.setHisOrdNum(order.getHisOrderNo());
                }

                refundRegisterVo.setHospitalCode(order.getOrgCode());
                refundRegisterVo.setBranchCode(order.getBranchCode());
                refundRegisterVo.setYytOrdNum(order.getOrderNo());
                refundRegisterVo.setYytRefOrdNum(order.getOrderNo());
                refundRegisterVo.setRefundMode(String.valueOf(order.getPayMode()));

                refundRegisterVo.setRefundTime(DateUtils.dateToString(new Date()));
                refundRegisterVo.setRefundReason("停诊退费");
                refundRegisterVo.setRegType(regType);

                ResCommon resCommon = HisifaceService.getHisifaceClient().refundRegister(refundRegisterVo);
//                logger.info("cancelRegInfo, his refundRegister:request={},response={}", com.alibaba.fastjson.JSON.toJSONString(refundRegisterVo), com.alibaba.fastjson.JSON.toJSONString(resCommon));
                Log.i(LogScene.REGISTER_STOP, "yyt.register.stop.reg.loop", LogParamType.REQUEST, refundRegisterVo.getYytOrdNum(),
                        "call his refundRegister request:" + JsonUtils.toJsonString(refundRegisterVo));
                Log.i(LogScene.REGISTER_STOP, "yyt.register.stop.reg.loop", LogParamType.RESPONSE, refundRegisterVo.getYytOrdNum(),
                        "call his refundRegister response:" + JsonUtils.toJsonString(resCommon));
                if (!"0".equals(resCommon.getResultCode())) {
                    //停诊异常终止流程，订单状态：变更，支付状态：待退费
                    order.setOrderStatusChange();
                    order.setPayStatusWaitRefund();
                    order.setUpdateTime(DateUtils.dateToString(new Date()));
                    BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));

                    //更新中间表状态
                    stopStatus = 2;
                    schedulerVo.setStopStatus(stopStatus);
                    schedulerVo.setOrderStatus(OrderExtVo.ORDER_STATUS_CHANGE);
                    schedulerVo.setPayStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    schedulerVo.setRefundHisResult((short) 2);
                    schedulerVo.setRefundHisCount((short) (schedulerVo.getRefundHisCount() == null ? 0 : schedulerVo.getRefundHisCount() + 1));
                    OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
                    continue;
                } else {
                    schedulerVo.setRefundHisResult((short) 1);
                    schedulerVo.setRefundHisCount((short) (schedulerVo.getRefundHisCount() == null ? 0 : schedulerVo.getRefundHisCount() + 1));
                }
            } else {
                schedulerVo.setRefundHisResult((short) 0);
            }
            /****调用his退费结束*****/

            /****调用第三方原渠道退费开始*****/
            if (isRefundPay) {
                Map<String, Object> jsonMap = new HashMap<String, Object>();
                jsonMap.put("hospital_code", order.getOrgCode());
                jsonMap.put("order_no", order.getOrderNo());
                if ("1".equals(order.getIsInsurance())) {
                    jsonMap.put("his_order_no", extraParams.get("CANCEL_BILL_NO"));
                    jsonMap.put("his_serial_no", extraParams.get("CANCEL_SERIAL_NO"));
                    jsonMap.put("refund_amount", order.getTotalAmount());
                } else {
                    jsonMap.put("his_order_no", order.getHisOrderNo());
                    jsonMap.put("refund_amount", order.getPayAmount());
                }

                jsonMap.put("refund_time", DateUtils.dateToString(new Date()));
                jsonMap.put("refund_reason", "停诊取消");
                jsonMap.put("refund_flag", 1);
                jsonMap.put("push_type", 0);
                Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
//                logger.info("cancelRegInfo：退费返回" + JsonUtils.toJsonString(refundResponse));
                Log.i(LogScene.REGISTER_STOP, "yyt.pay.refund.channel.origin", LogParamType.RESPONSE, order.getOrderNo(),
                        "yyt.pay.refund.channel.origin response:" + JsonUtils.toJsonString(refundResponse));
                if ("0".equals(refundResponse.getResultCode())) {
                    order.setPayStatusRefunded();
                    schedulerVo.setPayStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                    schedulerVo.setRefundPayResult((short) 1);
                    schedulerVo.setRefundPayCount((short) (schedulerVo.getRefundPayCount() == null ? 0 : schedulerVo.getRefundPayCount() + 1));
                } else {
                    //第三方退费异常，终止流程，订单状态：变更，支付状态：待退费
                    order.setOrderStatusChange();
                    order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
                    order.setUpdateTime(DateUtils.dateToString(new Date()));
                    BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));

                    //更新中间表状态
                    stopStatus = 2;
                    schedulerVo.setStopStatus(stopStatus);
                    schedulerVo.setOrderStatus(OrderExtVo.ORDER_STATUS_CHANGE);
                    schedulerVo.setPayStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    schedulerVo.setRefundPayResult((short) 2);
                    schedulerVo.setRefundHisCount((short) (schedulerVo.getRefundPayCount() == null ? 0 : schedulerVo.getRefundPayCount() + 1));
                    OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
                    continue;
                }
            } else {
                schedulerVo.setRefundPayResult((short) 0);//无需第三方退费
            }
            /****调用第三方原渠道退费end*****/

            if ("1".equals(isStopRegUnlock)) {
                //停诊执行号源释放
                CancelRegisterVo cancelRegisterVo = new CancelRegisterVo();
                cancelRegisterVo.setHospitalCode(order.getOrgCode());
                cancelRegisterVo.setBranchCode(order.getBranchCode());
                cancelRegisterVo.setHisOrdNum(order.getHisOrderNo());
                cancelRegisterVo.setCancelTime(DateUtils.dateToString(new Date()));
                cancelRegisterVo.setYytOrdNum(order.getOrderNo());
                cancelRegisterVo.setRegType(regType);

                ResCommon resCommon = HisifaceService.getHisifaceClient().cancelRegister(cancelRegisterVo);
//                logger.info("unlockRegInfo  his response=" + com.alibaba.fastjson.JSON.toJSONString(resCommon));
                Log.i(LogScene.REGISTER_STOP, "yyt.register.stop.reg.loop", LogParamType.RESPONSE, cancelRegisterVo.getYytOrdNum(),
                        "call his cancelRegister response:" + JsonUtils.toJsonString(resCommon));
                if ("0".equals(resCommon.getResultCode())) {
                    order.setOrderStatusChange();
                    order.setUpdateTime(DateUtils.dateToString(new Date()));
                    BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));

                    schedulerVo.setUnlockResult((short) 1);
                    schedulerVo.setUnlockCount((short) (schedulerVo.getUnlockCount() == null ? 0 : schedulerVo.getUnlockCount() + 1));
                } else {
                    //
                    stopStatus = 2;
                    schedulerVo.setStopStatus(stopStatus);
                    order.setOrderStatusChange();
                    order.setUpdateTime(DateUtils.dateToString(new Date()));
                    BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));

                    //更新中间表状态
                    schedulerVo.setOrderStatus(OrderExtVo.ORDER_STATUS_CHANGE);
                    schedulerVo.setUnlockResult((short) 2);
                    schedulerVo.setUnlockCount((short) (schedulerVo.getUnlockCount() == null ? 0 : schedulerVo.getUnlockCount() + 1));
//
                }
            } else {
                schedulerVo.setUnlockResult((short) 0);//无须解锁号源
            }
            schedulerVo.setOrderStatus(OrderExtVo.ORDER_STATUS_CHANGE);
            schedulerVo.setStopStatus(stopStatus);
            OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);

            order.setOrderStatusChange();
            BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));

        }//for
    }

    /**
     * 停改诊业务逻辑处理,一家医院的orderList
     *
     * @param order
     */
    private void dealReplace(OrderExtVo order, String replaceDoctorName, String replaceDoctorCode) {
        logger.info("替诊业务处理 record : {}", JsonUtils.toJsonString(order));
        String orgCode = order.getOrgCode();

        String stopRegMsgType = RegUtil.getRule(orgCode, RegUtil.STOP_REG_MSG_TYPE, "");//停诊消息推送方式

        OrderRegSchedulerVo schedulerVo = OrderService.getOrderClient().selectOrderRegSchedulerById(order.getId());
        if (schedulerVo == null) {
            schedulerVo = parseOrder(order);
            schedulerVo.setStopStatus((short) 1);//停诊处理状态，更改为成功
            OrderService.getOrderClient().addOrderRegScheduler(schedulerVo);//加到定时任务中间表
        }
        /****发送消息*****/
        if (stopRegMsgType.indexOf("2") >= 0) {
            //发送服务窗消息
            sendReplaceMessage(schedulerVo, replaceDoctorName, "2");
        }

        if (stopRegMsgType.indexOf("3") >= 0) {
            //发送公众号消息
            sendReplaceMessage(schedulerVo, replaceDoctorName, "1");
        }

        if (stopRegMsgType.indexOf("4") >= 0) {
            //停诊短信推送
            sendReplaceCodeAliDy(order, replaceDoctorName);
        }

        //更新订单表
        order.setOrderStatusReplace();
        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        extraParams.put("replace_doctor_name",replaceDoctorName);
        extraParams.put("replace_doctor_code", replaceDoctorCode);
        order.setExtraParams(JsonUtils.toJsonString(extraParams));
        BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));





    }


    /**
     * 中间表停诊任务执行
     * schedulerVo
     *
     * @param schedulerVo
     */
    public void dealStopSchedulerVo(OrderRegSchedulerVo schedulerVo) {
        String orgCode = schedulerVo.getOrgCode();

        String[] stopRegLimit = RegUtil.getRule(orgCode, RegUtil.STOP_REG_TIME_LIMIT, "1").split(",");//停诊退费时间限制
        int stopRegLimitValue = 1;//停诊退费时间限制
        int stopRegLimitType = Integer.parseInt(stopRegLimit[0]);
        if (stopRegLimit.length > 1) {
            stopRegLimitValue = Integer.parseInt(stopRegLimit[1]);
        }
        String isStopRegRefundHis = RegUtil.getRule(orgCode, RegUtil.IS_STOP_REG_REFUND_HIS, "1");//停诊是否执行退费
        String isStopRegUnlock = RegUtil.getRule(orgCode, RegUtil.IS_STOP_REG_UNLOCK, "1");//停诊是否执行号源释放
        String stopRegMsgType = RegUtil.getRule(orgCode, RegUtil.STOP_REG_MSG_TYPE, "");//停诊消息推送方式

        short stopStatus = 1;//停诊处理状态，初始为成功

        if (stopRegMsgType.indexOf("2") >= 0 && schedulerVo.getMsgSendResult() != null && 2 == schedulerVo.getMsgSendResult()) {
            //发送服务窗消息
            sendAlipayMessage(schedulerVo);
        }

        if (stopRegMsgType.indexOf("3") >= 0 && schedulerVo.getMsgSendResult() != null && 2 == schedulerVo.getMsgSendResult()) {
            //发送公众号消息
            sendWechatMessage(schedulerVo);
        }

        if (stopRegMsgType.indexOf("4") >= 0 && schedulerVo.getMsgSendResult() != null && 2 == schedulerVo.getMsgSendResult()) {
            //停诊短信推送
            sendCodeAliDy(schedulerVo, 1);
        }

        String regType = RegUtil.getRegType(schedulerVo.getScheduleTime().substring(0, 10));
        boolean isRefundHis;//是否his退费
        boolean isRefundPay;//是否第三方退费

        String beginTime = schedulerVo.getBeginTime();
        String endTime = schedulerVo.getEndTime();
        Date scheduleDate = DateUtils.StringToDateYMD(schedulerVo.getScheduleTime());//就诊日期
        //就诊开始时间
        Date scheduleStartTime = DateUtils.StringToDate(schedulerVo.getScheduleTime().substring(0, 10) + " " + beginTime + ":00");
        Date scheduleEndTime = DateUtils.StringToDate(schedulerVo.getScheduleTime().substring(0, 10) + " " + endTime + ":00");

        GregorianCalendar scheduleCalendar = new GregorianCalendar();
        Long nowTime = new Date().getTime();
        Long overTime = null;
        /**
         *  取消挂号截止时间点
         *  1、不限制 就诊当天几点
         *  2、就诊当天几点
         *  3、就诊时间段开始前多少分钟
         *  4、就诊时间段结束前多少分钟
         */
        switch (stopRegLimitType) {
            case 1:
                //不限制情况  当前时间+1 始终使overTime > nowTime
                overTime = nowTime + 1;
                break;
            case 2:
                //2、就诊当天几点
                scheduleCalendar.setTime(scheduleDate);
                scheduleCalendar.set(Calendar.HOUR_OF_DAY, stopRegLimitValue);
                overTime = scheduleCalendar.getTimeInMillis();
                break;
            case 3:
                //3、就诊时间段开始前多少分钟
                scheduleCalendar.setTime(scheduleStartTime);
                overTime = scheduleCalendar.getTimeInMillis() - stopRegLimitValue * 60 * 1000;
                break;
            case 4:
                //就诊时间段结束前多少分钟
                scheduleCalendar.setTime(scheduleEndTime);
                overTime = scheduleCalendar.getTimeInMillis() - stopRegLimitValue * 60 * 1000;
                break;
            case 5:
                scheduleCalendar.setTime(scheduleDate);
                scheduleCalendar.add(Calendar.DATE, -1);
                scheduleCalendar.set(Calendar.HOUR_OF_DAY, stopRegLimitValue);
                overTime = scheduleCalendar.getTimeInMillis();
                break;
            case 6:
                //不允许情况  当前时间11 始终使overTime < nowTime
                overTime = nowTime - 1;
                break;
        }

        if (nowTime >= overTime) {
            //超出时间限制或不允许退费
            isRefundHis = false;
            isRefundPay = false;
        } else {
            if ("1".equals(isStopRegRefundHis)) {//停诊是否执行退费通知
                isRefundHis = true;
            } else {
                isRefundHis = false;
            }
            isRefundPay = true;
        }

        /****调用his退费开始*****/
        if (isRefundHis) {
            if (schedulerVo.getRefundHisResult() == null || schedulerVo.getRefundHisResult() != 1) {
                RefundRegisterVo refundRegisterVo = new RefundRegisterVo();
                if ("1".equals(schedulerVo.getIsInsurance())) {
                    //医保退款
                    refundRegisterVo.setRefundAmount(String.valueOf(schedulerVo.getTotalAmount()));
                    Map<String, String> ybMap = new HashedMap();
                    ybMap.put("cancel_serial_no", schedulerVo.getCancelSerialNo());
                    ybMap.put("cancel_bill_no", schedulerVo.getCancelBillNo());
                    refundRegisterVo.setExtendParams(JSONObject.toJSONString(ybMap));
                } else {
                    //            refundRegisterVo.setRefundAmount(String.valueOf(order.getPayAmount()));
                    refundRegisterVo.setRefundAmount("2000");//test
                    refundRegisterVo.setHisOrdNum(schedulerVo.getHisOrderNo());
                }

                refundRegisterVo.setHospitalCode(schedulerVo.getOrgCode());
                refundRegisterVo.setBranchCode(schedulerVo.getBranchCode());
                refundRegisterVo.setYytOrdNum(schedulerVo.getOrderNo());
                refundRegisterVo.setYytRefOrdNum(schedulerVo.getOrderNo());
                refundRegisterVo.setRefundMode(String.valueOf(schedulerVo.getPayMode()));

                refundRegisterVo.setRefundTime(DateUtils.dateToString(new Date()));
                refundRegisterVo.setRefundReason("停诊退费");
                refundRegisterVo.setRegType(regType);

                ResCommon resCommon = HisifaceService.getHisifaceClient().refundRegister(refundRegisterVo);
                logger.info("cancelRegInfo, his refundRegister:request={},response={}", com.alibaba.fastjson.JSON.toJSONString(refundRegisterVo), com.alibaba.fastjson.JSON.toJSONString(resCommon));
                if (!"0".equals(resCommon.getResultCode())) {
                    //停诊异常终止流程，订单状态：变更，支付状态：待退费

                    //更新中间表状态
                    stopStatus = 2;
                    schedulerVo.setStopStatus(stopStatus);
                    schedulerVo.setRefundHisResult((short) 2);
                    schedulerVo.setRefundHisCount((short) (schedulerVo.getRefundHisCount() == null ? 0 : schedulerVo.getRefundHisCount() + 1));
                    OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
                    return;
                } else {
                    schedulerVo.setRefundHisResult((short) 1);
                    schedulerVo.setRefundHisCount((short) (schedulerVo.getRefundHisCount() == null ? 0 : schedulerVo.getRefundHisCount() + 1));
                }
            }
        } else {
            schedulerVo.setRefundHisResult((short) 0);
        }
        /****调用his退费结束*****/

        /****调用第三方原渠道退费开始*****/
        if (isRefundPay) {
            if (schedulerVo.getRefundPayResult() == null || schedulerVo.getRefundPayResult() != 1) {
                Map<String, Object> jsonMap = new HashMap<String, Object>();
                jsonMap.put("hospital_code", schedulerVo.getOrgCode());
                jsonMap.put("order_no", schedulerVo.getOrderNo());
                if ("1".equals(schedulerVo.getIsInsurance())) {
                    jsonMap.put("his_order_no", schedulerVo.getCancelBillNo());
                    jsonMap.put("his_serial_no", schedulerVo.getCancelSerialNo());
                    jsonMap.put("refund_amount", schedulerVo.getTotalAmount());
                } else {
                    jsonMap.put("his_order_no", schedulerVo.getHisOrderNo());
                    jsonMap.put("refund_amount", schedulerVo.getPayAmount());
                }

                jsonMap.put("refund_time", DateUtils.dateToString(new Date()));
                jsonMap.put("refund_reason", "停诊取消");
                jsonMap.put("refund_flag", 1);
                jsonMap.put("push_type", 0);
                Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
                logger.info("cancelRegInfo：退费返回" + JsonUtils.toJsonString(refundResponse));
                if ("0".equals(refundResponse.getResultCode())) {
//                    order.setPayStatusRefunded();
                    schedulerVo.setPayStatus(OrderExtVo.ORDER_PAY_STATUS_REFUNDED);
                    schedulerVo.setRefundPayResult((short) 1);
                    schedulerVo.setRefundPayCount((short) (schedulerVo.getRefundPayCount() == null ? 0 : schedulerVo.getRefundPayCount() + 1));
                } else {
                    //第三方退费异常，终止流程，订单状态：变更，支付状态：待退费
//                    order.setOrderStatusChange();
//                    order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
//                    order.setUpdateTime(DateUtils.dateToString(new Date()));
//                    BaseService.callUnderlineFromInternal("","yyt.base.order.update", JsonUtils.toJsonString(order));

                    //更新中间表状态
                    stopStatus = 2;
                    schedulerVo.setStopStatus(stopStatus);
                    schedulerVo.setPayStatus(OrderExtVo.ORDER_PAY_STATUS_WAIT_REFUND);
                    schedulerVo.setRefundPayResult((short) 2);
                    schedulerVo.setRefundPayCount((short) (schedulerVo.getRefundPayCount() == null ? 0 : schedulerVo.getRefundPayCount() + 1));
                    OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
                    return;
                }
            }
        } else {
            schedulerVo.setRefundPayResult((short) 0);//无需第三方退费
        }
        /****调用第三方原渠道退费end*****/

        if ("1".equals(isStopRegUnlock)) {
            if (schedulerVo.getUnlockResult() == null || schedulerVo.getUnlockResult() != 1) {
                //停诊执行号源释放
                CancelRegisterVo cancelRegisterVo = new CancelRegisterVo();
                cancelRegisterVo.setHospitalCode(schedulerVo.getOrgCode());
                cancelRegisterVo.setBranchCode(schedulerVo.getBranchCode());
                cancelRegisterVo.setHisOrdNum(schedulerVo.getHisOrderNo());
                cancelRegisterVo.setCancelTime(DateUtils.dateToString(new Date()));
                cancelRegisterVo.setYytOrdNum(schedulerVo.getOrderNo());
                cancelRegisterVo.setRegType(regType);

                ResCommon resCommon = HisifaceService.getHisifaceClient().cancelRegister(cancelRegisterVo);
                logger.info("unlockRegInfo  his response=" + com.alibaba.fastjson.JSON.toJSONString(resCommon));
                if ("0".equals(resCommon.getResultCode())) {
                    stopStatus = 1;
                    schedulerVo.setUnlockResult((short) 1);

                } else {
                    stopStatus = 2;
                    schedulerVo.setStopStatus(stopStatus);
                    schedulerVo.setUnlockResult((short) 2);
                }
                schedulerVo.setUnlockCount((short) (schedulerVo.getUnlockCount() == null ? 0 : schedulerVo.getUnlockCount() + 1));
            }
        } else {
            schedulerVo.setUnlockResult((short) 0);//无须解锁号源
        }

        schedulerVo.setStopStatus(stopStatus);
        OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);

        //把订单状态改成变更
        Map<String, String> ordQueryMap = new HashMap<String, String>();
        ordQueryMap.put("order_no", schedulerVo.getOrderNo());
        Response ordResponse = BaseService.callUnderlineFromInternal("",
                "yyt.base.order.by.order.no.get", JsonUtils.toJsonString(ordQueryMap));
        if ("0".equals(ordResponse.getResultCode())) {
            OrderExtVo order = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);
            order.setOrderStatus(OrderExtVo.ORDER_STATUS_CHANGE);
            BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(order));
        }

    }

    /**
     * 转换成订单定时任务中间表实体
     *
     * @param order
     * @return
     */
    private OrderRegSchedulerVo parseOrder(OrderExtVo order) {
        OrderRegSchedulerVo vo = new OrderRegSchedulerVo();
        vo.setId(order.getId());
        vo.setOrgCode(order.getOrgCode());
        vo.setOrgName(order.getOrgName());
        vo.setOrderNo(order.getOrderNo());
        vo.setBranchCode(order.getBranchCode());
        vo.setDoctorName(order.getDoctorName());
        vo.setDeptName(order.getDeptName());
        vo.setPlatformOrgAppCode(order.getPlatformOrgAppCode());
        vo.setUserName(order.getUserName());
        vo.setUserMobile(order.getUserMobile());
        vo.setOpenId(order.getOpenId());
        vo.setScheduleTime(order.getScheduleTime());
        vo.setIsInsurance(order.getIsInsurance());
        vo.setHisOrderNo(order.getHisOrderNo());
        vo.setPayMode(order.getPayMode());
        vo.setOrderStatus(order.getOrderStatus());
        vo.setPayStatus(order.getPayStatus());
        vo.setTotalAmount(order.getTotalAmount());
        vo.setPayAmount(order.getPayAmount());
        vo.setPaymentDealId(order.getPaymentDealId());
        vo.setCreatedTime(order.getCreatedTime());

        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        String beginTime = "00:00", endTime = "23:59";
        if (extraParams != null) {
            beginTime = (String) extraParams.get("begin_time");
            endTime = (String) extraParams.get("end_time");
        }
        vo.setBeginTime(beginTime);
        vo.setEndTime(endTime);
        vo.setCancelSerialNo((String) extraParams.get("cancel_serial_no"));
        vo.setCancelBillNo((String) extraParams.get("cancel_bill_no"));
        vo.setPayAppId(order.getPayAppId());
        return vo;
    }

    private void refundStopReg(OrderExtVo order, String regType) {
        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        RefundRegisterVo refundRegisterVo = new RefundRegisterVo();
        if ("1".equals(order.getIsInsurance())) {
            //医保退款
            refundRegisterVo.setRefundAmount(String.valueOf(order.getTotalAmount()));
            Map<String, String> ybMap = new HashedMap();
            ybMap.put("cancel_serial_no", (String) extraParams.get("cancel_serial_no"));
            ybMap.put("cancel_bill_no", (String) extraParams.get("cancel_bill_no"));
            refundRegisterVo.setExtendParams(JSONObject.toJSONString(ybMap));
        } else {
            //            refundRegisterVo.setRefundAmount(String.valueOf(order.getPayAmount()));
            refundRegisterVo.setRefundAmount("2000");//test
            refundRegisterVo.setHisOrdNum(order.getHisOrderNo());
        }

        refundRegisterVo.setHospitalCode(order.getOrgCode());
        refundRegisterVo.setBranchCode(order.getBranchCode());
        refundRegisterVo.setYytOrdNum(order.getOrderNo());
        refundRegisterVo.setYytRefOrdNum(order.getOrderNo());
        refundRegisterVo.setRefundMode(String.valueOf(order.getPayMode()));

        refundRegisterVo.setRefundTime(DateUtils.dateToString(new Date()));
        refundRegisterVo.setRefundReason("停诊");
        refundRegisterVo.setRegType(regType);

        ResCommon resCommon = HisifaceService.getHisifaceClient().refundRegister(refundRegisterVo);
        logger.info("cancelRegInfo, his refundRegister:request={},response={}", com.alibaba.fastjson.JSON.toJSONString(refundRegisterVo), com.alibaba.fastjson.JSON.toJSONString(resCommon));
        if (!"0".equals(resCommon.getResultCode())) {
//            response.setResultCodeAndMessage("6101", "调用医院接口退费失败");
//            return response;
        }

        order.setOrderStatusCancel();//his退费成功，订单状态改成取消

        //第三方原渠道退费
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("hospital_code", order.getOrgCode());
        jsonMap.put("order_no", order.getOrderNo());
        if ("1".equals(order.getIsInsurance())) {
            jsonMap.put("his_order_no", extraParams.get("CANCEL_BILL_NO"));
            jsonMap.put("his_serial_no", extraParams.get("CANCEL_SERIAL_NO"));
            jsonMap.put("refund_amount", order.getTotalAmount());
        } else {
            jsonMap.put("his_order_no", order.getHisOrderNo());
            jsonMap.put("refund_amount", order.getPayAmount());
        }

        jsonMap.put("refund_time", DateUtils.dateToString(new Date()));
        jsonMap.put("refund_reason", "挂号取消");
        jsonMap.put("refund_flag", 1);
        jsonMap.put("push_type", 0);
        Response refundResponse = PayService.callUnderlineFromInternal("", "yyt.pay.refund.channel.origin", JsonUtils.toJsonString(jsonMap));
        logger.info("cancelRegInfo：退费返回" + JsonUtils.toJsonString(refundResponse));
        if ("0".equals(refundResponse.getResultCode())) {
            order.setPayStatusRefunded();
//            response.setResultCodeAndMessage("0", "取消挂号成功");
        } else {
            order.setPayStatusWaitRefund();//第三方退费失败，状态改成待退费
//            response.setResultCodeAndMessage(refundResponse.getResultCode(), refundResponse.getResultMessage());
        }

        //更新订单状态
        logger.info("cancelRegInfo, 退费成功，更改订单状态 updateOrder =" + JSONObject.toJSONString(order));
        BaseService.callUnderlineFromInternal("",
                "yyt.base.order.update", JsonUtils.toJsonString(order));
    }

    /**
     * 发送停改诊短信
     *
     * @param schedulerVo
     * @param type
     * @return
     */
    public void sendCodeAliDy(OrderRegSchedulerVo schedulerVo, int type) {
        logger.info("停改诊短信推送开始..........record: {}...........", JSONObject.toJSONString(schedulerVo));
        try {
            //发送短信
            Map<String, Object> dataMap = new HashedMap();
            dataMap.put("user_type", "5");
            dataMap.put("to_user", schedulerVo.getUserMobile());
            if (type == 2) {
                dataMap.put("msg_type", 62);
            } else {
                dataMap.put("msg_type", 61);
            }
            JSONObject content = new JSONObject();
            content.put("hospital_name", schedulerVo.getOrgName());
            content.put("user_name", schedulerVo.getUserName());
            content.put("doctor_name", schedulerVo.getDoctorName());
            content.put("dept_name", schedulerVo.getDeptName());
            String scheduleTime = schedulerVo.getScheduleTime();
            if (scheduleTime != null && scheduleTime.length() > 10) {
                scheduleTime = scheduleTime.substring(0, 10);
                scheduleTime += " " + schedulerVo.getBeginTime() + "-" + schedulerVo.getEndTime();
            }
            content.put("schedule_date", scheduleTime);
            dataMap.put("msg_content", content);
            Response response = MessageService.callUnderlineFromInternal("", "yyt.message.msg.sms.send", JsonUtils.toJsonString(dataMap));
//            logger.info("停诊调用短信返回:"+ JsonUtils.toJsonString(response));
            Log.i(LogScene.REGISTER_STOP, "yyt.message.msg.sms.send", LogParamType.RESPONSE, schedulerVo.getOrderNo(),
                    "停诊调用短信返回:" + JsonUtils.toJsonString(response));
            if ("0".equals(response.getResultCode())) {
                schedulerVo.setMsgSendResult((short) 1);
            } else {
                schedulerVo.setMsgSendResult((short) 2);
            }

        } catch (Exception e) {
            e.printStackTrace();
            schedulerVo.setMsgSendResult((short) 2);
        }
        schedulerVo.setMsgSendCount((short) (schedulerVo.getMsgSendCount() == null ? 0 : schedulerVo.getMsgSendCount() + 1));
        OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
    }

    /**
     * 发送服务窗消息
     *
     * @param schedulerVo
     * @return
     */
    public void sendAlipayMessage(OrderRegSchedulerVo schedulerVo) {
        logger.info("服务窗停改诊服务窗消息推送开始..........schedulerVo: {}...........", JSONObject.toJSONString(schedulerVo));
        try {
            String url=yaml.getProperty("order.reg.url")+"order_no="+schedulerVo.getOrderNo()+"&app_code="+schedulerVo.getPlatformOrgAppCode()+"&open_id="+schedulerVo.getOpenId()+"&app_id="+schedulerVo.getPayAppId();
            //消息重构
            AppMessageVo appMessageVo = new AppMessageVo();
            appMessageVo.setPlatformOrgAppCode(schedulerVo.getPlatformOrgAppCode());
            appMessageVo.setPlatformTemplateCode(TemplateCode.STOP_REG_MES.getCode());
            appMessageVo.setPlatformType((short) 2);
            appMessageVo.setDevOrgCode(schedulerVo.getOrgCode());
            appMessageVo.setLibraryTemplateType((short) 3);
            appMessageVo.setUrl(url);
            appMessageVo.setOpenId(schedulerVo.getOpenId());
            Map<String,String> map =new HashMap<String,String>();
            map.put("hospitalName" , schedulerVo.getOrgName()==null?"":schedulerVo.getOrgName());
            map.put("deptName" , schedulerVo.getDeptName()==null?"":schedulerVo.getDeptName());
            map.put("doctorName" , schedulerVo.getDoctorName()==null?"":schedulerVo.getDoctorName());
            map.put("time" , "医生临时停诊，下次开诊时间请留意医院公告");
            map.put("remark" , "订单号：" + schedulerVo.getOrderNo());
            appMessageVo.setMsgContentMap(map);
            Log.i(LogScene.REGISTER_STOP,"MessageServiceImpl.sendAppMessage", LogParamType.REQUEST,schedulerVo.getOrderNo(),
                    "停改诊服务窗消息推送接口,入参request="  + JsonUtils.toJsonString(appMessageVo));
            ResponseObject responseObject = MessageService.getMessageClient().sendAppMessage(appMessageVo);
            Log.i(LogScene.REGISTER_STOP,"MessageServiceImpl.sendAppMessage", LogParamType.RESPONSE,schedulerVo.getOrderNo(),
                    "停改诊服务窗消息推送,调用message模块, 返回response="  + JsonUtils.toJsonString(responseObject));

            if ("0".equals(responseObject.getResultCode())) {
                schedulerVo.setMsgSendResult((short) 1);
            } else {
                schedulerVo.setMsgSendResult((short) 2);
            }

        }catch (Exception e){
            schedulerVo.setMsgSendResult((short) 2);
            e.printStackTrace();
        }
        schedulerVo.setMsgSendCount((short) (schedulerVo.getMsgSendCount()==null?0:schedulerVo.getMsgSendCount() + 1));
        OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
    }

    /**
     * 发送微信公众号消息
     *
     * @param schedulerVo
     * @return
     */
    public void sendWechatMessage(OrderRegSchedulerVo schedulerVo) {
        logger.info("微信停改诊服务窗消息推送开始..........schedulerVo: {}...........", JSONObject.toJSONString(schedulerVo));

        try {
            String url=yaml.getProperty("order.reg.url")+"order_no="+schedulerVo.getOrderNo()+"&app_code="+schedulerVo.getPlatformOrgAppCode()+"&open_id="+schedulerVo.getOpenId()+"&app_id="+schedulerVo.getPayAppId();
            //消息重构
            AppMessageVo appMessageVo = new AppMessageVo();
            appMessageVo.setPlatformOrgAppCode(schedulerVo.getPlatformOrgAppCode());
            appMessageVo.setPlatformTemplateCode(TemplateCode.STOP_REG_MES.getCode());
            appMessageVo.setPlatformType((short) 1);
            appMessageVo.setDevOrgCode(schedulerVo.getOrgCode());
            appMessageVo.setLibraryTemplateType((short) 3);
            appMessageVo.setUrl(url);
            appMessageVo.setOpenId(schedulerVo.getOpenId());
            Map<String,String> map =new HashMap<String,String>();
            map.put("hospitalName" , schedulerVo.getOrgName()==null?"":schedulerVo.getOrgName());
            map.put("deptName" , schedulerVo.getDeptName()==null?"":schedulerVo.getDeptName());
            map.put("doctorName" , schedulerVo.getDoctorName()==null?"":schedulerVo.getDoctorName());
            map.put("time" , "医生临时停诊，下次开诊时间请留意医院公告");
            map.put("remark" , "订单号：" + schedulerVo.getOrderNo());
            appMessageVo.setMsgContentMap(map);

            Log.i(LogScene.REGISTER_STOP, "MessageServiceImpl.sendAppMessage", LogParamType.REQUEST, schedulerVo.getOrderNo(),
                    "微信停改诊消息推送接口,入参request=" + JsonUtils.toJsonString(appMessageVo));
            ResponseObject responseObject = MessageService.getMessageClient().sendAppMessage(appMessageVo);
            Log.i(LogScene.REGISTER_STOP, "MessageServiceImpl.sendAppMessage", LogParamType.RESPONSE, schedulerVo.getOrderNo(),
                    "微信停改诊消息推送接口,调用message模块, 返回response=" + JsonUtils.toJsonString(responseObject));

            if ("0".equals(responseObject.getResultCode())) {
                schedulerVo.setMsgSendResult((short) 1);
            } else {
                schedulerVo.setMsgSendResult((short) 2);
            }

        }catch (Exception e){
            schedulerVo.setMsgSendResult((short) 2);
            e.printStackTrace();
        }
        schedulerVo.setMsgSendCount((short) (schedulerVo.getMsgSendCount()==null?0:schedulerVo.getMsgSendCount() + 1));
        OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
    }

    /**
     * 发送微信公众号或支付宝服务窗消息
     *
     * @param schedulerVo
     * @param platformType 1 微信 "2"
     * @return
     */
    public void sendReplaceMessage(OrderRegSchedulerVo schedulerVo, String replaceDoctorName, String platformType) {
        logger.info("替诊消息推送开始..........schedulerVo: {}...........", JSONObject.toJSONString(schedulerVo));
        //发送短信
        try {
            String platformTypeName = "";
            if(Short.valueOf(platformType) == 1){
                platformTypeName = "微信";
            }else{
                platformTypeName = "支付宝";
            }

            String url = yaml.getProperty("order.reg.url") + "order_no=" + schedulerVo.getOrderNo() + "&app_code=" + schedulerVo.getPlatformOrgAppCode() + "&open_id=" + schedulerVo.getOpenId() + "&app_id=" + schedulerVo.getPayAppId();
            //消息重构
            AppMessageVo appMessageVo = new AppMessageVo();
            appMessageVo.setPlatformOrgAppCode(schedulerVo.getPlatformOrgAppCode());
            appMessageVo.setPlatformTemplateCode(TemplateCode.REPLACE_REG_MSG.getCode());
            appMessageVo.setPlatformType(Short.valueOf(platformType));
            appMessageVo.setDevOrgCode(schedulerVo.getOrgCode());
            appMessageVo.setLibraryTemplateType((short) 3);
            appMessageVo.setUrl(url);
            appMessageVo.setOpenId(schedulerVo.getOpenId());
            Map<String,String> map =new HashMap<String,String>();
            map.put("userName" , schedulerVo.getUserName() == null ? "" : schedulerVo.getUserName());
            map.put("orgName" , schedulerVo.getOrgName() == null ? "" : schedulerVo.getOrgName());
            map.put("doctorName" , schedulerVo.getDoctorName()==null?"":schedulerVo.getDoctorName());
            map.put("replaceDoctorName" , replaceDoctorName == null ? "" : replaceDoctorName);
            String scheduleTime = schedulerVo.getScheduleTime();
            if (scheduleTime != null && scheduleTime.length() > 10) {
                scheduleTime = scheduleTime.substring(0, 10);
                scheduleTime += " " + schedulerVo.getBeginTime() + "-" + schedulerVo.getEndTime();
            }
            map.put("time" , scheduleTime);
            appMessageVo.setMsgContentMap(map);

            Log.i(LogScene.REGISTER_REPLACE, "MessageServiceImpl.sendAppMessage", LogParamType.REQUEST, schedulerVo.getOrderNo(),
                    platformTypeName + "替诊消息推送接口,入参request=" + JsonUtils.toJsonString(appMessageVo));
            ResponseObject responseObject = MessageService.getMessageClient().sendAppMessage(appMessageVo);
            Log.i(LogScene.REGISTER_REPLACE, "MessageServiceImpl.sendAppMessage", LogParamType.RESPONSE, schedulerVo.getOrderNo(),
                    platformTypeName + "替诊消息推送接口,调用message模块, 返回response=" + JsonUtils.toJsonString(responseObject));

            if ("0".equals(responseObject.getResultCode())) {
                schedulerVo.setMsgSendResult((short) 1);
            } else {
                schedulerVo.setMsgSendResult((short) 2);
            }

        } catch (Exception e) {
            schedulerVo.setMsgSendResult((short) 2);
            e.printStackTrace();
        }
        schedulerVo.setMsgSendCount((short) (schedulerVo.getMsgSendCount() == null ? 0 : schedulerVo.getMsgSendCount() + 1));
        OrderService.getOrderClient().updateOrderRegScheduler(schedulerVo);
    }

    /**
     * 发送替诊短信
     *
     * @param order
     * @param replaceDoctorName
     */
    private void sendReplaceCodeAliDy(OrderExtVo order, String replaceDoctorName) {
        Map<String, Object> smsMap = new HashedMap();
        smsMap.put("org_code", order.getOrgCode());
        smsMap.put("to_user", order.getUserMobile());
        smsMap.put("template_code", "sms_stop_001");
        smsMap.put("platform_org_app_code", order.getPlatformOrgAppCode());
        Map<String, String> contentMap = JsonUtils.parseObject(JsonUtils.toJsonString(order), Map.class);
        Map<String, String> extraParamsMap = JsonUtils.parseObject(order.getExtraParams(), Map.class);
        contentMap.putAll(extraParamsMap);
        String scheduleTime = order.getScheduleTime();
        if (scheduleTime != null && scheduleTime.length() > 10) {
            scheduleTime = scheduleTime.substring(0, 10);
            scheduleTime += " " + extraParamsMap.get("begin_time") + "-" + extraParamsMap.get("end_time");
        }
        contentMap.put("schedule_time", scheduleTime);
        contentMap.put("replace_doctor_name", replaceDoctorName);
        smsMap.put("msg_content", contentMap);

        Response messageResponse = MessageService.callHumpFromInternal("yyt.message.msg.sms.send", JsonUtils.toJsonString(smsMap));
        logger.info("订单号" + order.getOrderNo() + ", 发送替诊短信,调用message模块,yyt.message.msg.sms.send request={}，response={}",
                JsonUtils.toJsonString(smsMap), JsonUtils.toJsonString(messageResponse));
    }


    /**
     * 发送微信公众号或支付宝服务窗消息
     *
     * @param schedulerVo
     * @param platformType 1 微信 "2"
     * @return
     */
    public void sendChangeMessage(OrderExtVo schedulerVo, StopRegisterVoResponse stopRegVo, String platformType) {
        logger.info("改诊消息推送开始..........order: {}...........", JSONObject.toJSONString(schedulerVo));
        logger.info("改诊消息推送开始..........stopRegVo: {}...........", JSONObject.toJSONString(stopRegVo));
        //发送短信
        String method = "yyt.message.msg.template.send";
        try {
            String url = yaml.getProperty("order.reg.url") + "order_no=" + schedulerVo.getOrderNo() + "&app_code=" + schedulerVo.getPlatformOrgAppCode() + "&open_id=" + schedulerVo.getOpenId() + "&app_id=" + schedulerVo.getPayAppId();
            String platformTypeName = "";
            if(Short.valueOf(platformType) == 1){
                platformTypeName = "微信";
            }else{
                platformTypeName = "支付宝";
            }

            //消息重构
            AppMessageVo appMessageVo = new AppMessageVo();
            appMessageVo.setPlatformOrgAppCode(schedulerVo.getPlatformOrgAppCode());
            appMessageVo.setPlatformTemplateCode(TemplateCode.CHANGE_REG_MSG.getCode());
            appMessageVo.setPlatformType(Short.valueOf(platformType));
            appMessageVo.setDevOrgCode(schedulerVo.getOrgCode());
            appMessageVo.setLibraryTemplateType((short) 3);
            appMessageVo.setUrl(url);
            appMessageVo.setOpenId(schedulerVo.getOpenId());
            Map<String,String> map =new HashMap<String,String>();
            map.put("userName" , schedulerVo.getUserName() == null ? "" : schedulerVo.getUserName());
            map.put("orgName" , schedulerVo.getOrgName() == null ? "" : schedulerVo.getOrgName());
            map.put("deptName" , schedulerVo.getDeptName() == null ? "" : schedulerVo.getDeptName());
            map.put("doctorName" , schedulerVo.getDoctorName()==null?"":schedulerVo.getDoctorName());
            String orginRegisterDate = stopRegVo.getRegisterDate().substring(5)+" "+ stopRegVo.getBeginTime()+"-"+stopRegVo.getEndTime();
            map.put("exTime" , orginRegisterDate);
            String revisionDate ="";
            if(stopRegVo.getRevisionBeginTime() !=null &&stopRegVo.getRevisionBeginTime()!=null){
                revisionDate = stopRegVo.getRevisionDate().substring(5)+" "+ stopRegVo.getRevisionBeginTime()+"-"+stopRegVo.getRevisionBeginTime();
            }else {
                revisionDate = stopRegVo.getRevisionDate().substring(5)+" "+ stopRegVo.getBeginTime()+"-"+stopRegVo.getEndTime();
            }
            map.put("time" , revisionDate);
            appMessageVo.setMsgContentMap(map);

            Log.i(LogScene.REGISTER_CHANGE, "MessageServiceImpl.sendAppMessage", LogParamType.REQUEST, schedulerVo.getOrderNo(),
                    platformTypeName + "改诊消息推送接口,入参request=" + JsonUtils.toJsonString(appMessageVo));
            ResponseObject responseObject = MessageService.getMessageClient().sendAppMessage(appMessageVo);
            Log.i(LogScene.REGISTER_CHANGE, "MessageServiceImpl.sendAppMessage", LogParamType.RESPONSE, schedulerVo.getOrderNo(),
                    platformTypeName + "改诊消息推送接口,调用message模块, 返回response=" + JsonUtils.toJsonString(responseObject));

        } catch (Exception e) {
            logger.error("改诊发送消息异常 order_no ={},errMsg={}",schedulerVo.getOrderNo(),e);
            Log.e(LogScene.REGISTER_CHANGE,"改诊发送消息异常 order_no ={}",schedulerVo.getOrderNo(),e.getMessage());
        }

    }


}
